﻿angular.module('app')
    .controller('UserCtrl', ['$rootScope',
        "$scope", "WorkContextSrv", 'ngTableParams', '$filter', '$stateParams', 'UserSrv', '$timeout', 'globalConfig', '$interval', 'helperSrv', function ($rootScope, $scope, workContextSrv, ngTableParams, $filter, $stateParams, userSrv, $timeout, globalConfig, $interval, helperSrv) {
            var currentUser = workContextSrv.getCurrentUser();
            var tm;

            $timeout(function () {
                $rootScope.$broadcast('hidePreloading');
            }, 500);

            //set active tab
            $scope.currentTab = "info";
            //change tab function
            $scope.changeTab = function (tab) {
                $scope.currentTab = tab;
            };
            //check current tab
            $scope.isTab = function (tab) {
                return $scope.currentTab == tab;
            };

            $scope.onSubmitting = false;

            //convert birtday format
            var birtdayFormated = currentUser.birthday === null ? '' : helperSrv.convertDateObjectToFormatedString(new Date(currentUser.birthday));

            //create usermodel
            $scope.currentUser = {
                UserName: currentUser.userName,
                //Birthday: birtdayFormated,
                BirthdayStr: birtdayFormated,
                Email: currentUser.email,
                FirstName: currentUser.firstName,
                LastName: currentUser.lastName,
                Gender: currentUser.gender,
                Note: currentUser.note,
                Phone: currentUser.phone,
                Position: currentUser.position,
                Department: currentUser.department,
                PhotoPath: currentUser.photoPath,
            };

            $scope.birthdayFormat = globalConfig.dateFormat;

            //max selectable year
            $scope.maxBirthdateYear = new Date().getFullYear() - 10;

            var postUrl = "api/users/avatar/" + currentUser.userName + "?name=" + currentUser.userName;
            var filesList = [];
            $scope.onAvatarUploading = false;
            var fileSize = globalConfig.imageSize;

            //get filename from path
            var getFileNameFromPath = function (fullPath) {
                var index = fullPath.lastIndexOf("\\") + 1;
                if (index === 0) {
                    index = fullPath.lastIndexOf("/") + 1;
                }
                var filename = fullPath.substr(index);

                return filename;
            };

            //validate file function
            function validateFile(fileName, filesi) {
                var validFile = true;
                //validate extension
                if (!(globalConfig.regexAllowedImageExtension).test(fileName)) {
                    alert('Only accepted file types: ' + globalConfig.regexAllowedImageExtension);
                    validFile = false;
                }
                //validate fileSize (not support in <= IE 9)
                if (filesi > 0 && filesi > fileSize) { // 2mb
                    alert('Please upload a smaller file, max size is 0.5 MB (512kb)');
                    validFile = false;
                }

                return validFile;
            }

            //file change function
            function fileChange() {
                var fileName = getFileNameFromPath(jQuery(this).val());
                jQuery(this).removeClass("file-error");
                if (!validateFile(fileName, 0)) {
                    jQuery(this).addClass("file-error");
                } else {
                    $scope.onAvatarUploading = true;
                    //create unique id
                    var frameId = "upload_frame_" + new Date().getTime();
                    //append iframe for post
                    jQuery("#userinfoform").append('<iframe id="' + frameId + '" name="' + frameId + '" class="hidden"></iframe>');
                    //handle event when iframe loaded
                    jQuery('#' + frameId).on('load', function () {
                        //hide indicator
                        $scope.onAvatarUploading = false;
                        //fire 'replyadded' event
                        var $e = jQuery(this);
                        $timeout(function () {
                            $scope.$broadcast('avataruploaded', $e.contents().find('pre').html());
                        });
                        $timeout(function () {
                            //remove iframe
                            jQuery(this).remove();
                            jQuery("#user-avatar").find("#avataruploader").remove();
                            jQuery("<input type='file' id='avataruploader' class='ie-file active-file' name='file' />").appendTo(jQuery("#user-avatar")).bind("change", fileChange);
                        }, 500);
                    });
                    //get form
                    var $form = jQuery("#userinfoform");

                    //add attribute to form
                    $form.attr('action', postUrl);
                    $form.attr('method', 'post');
                    $form.attr('enctype', 'multipart/form-data');
                    //change target to iframe and submit
                    $form.attr('target', frameId).submit();
                }
            }

            //Setup avatar upload when html ready
            $scope.onProfileLoad = function () {
                var config = {
                    dropZone: jQuery('#user-avatar-uploader'),
                    autoUpload: false
                };

                $timeout(function () {
                    if (helperSrv.isIe() === 9) {
                        jQuery("<input type='file' id='avataruploader' class='ie-file active-file' name='file' />").appendTo(jQuery("#user-avatar")).bind("change", fileChange);
                    } else {
                        //setup file upload
                        jQuery('<input type="file" name="avatar" id="avataruploader" /> ').appendTo(jQuery("#user-avatar"));
                        $timeout(function () {
                            jQuery("#avataruploader").fileupload(config)
                                .bind('fileuploadadd', function (e, data) {
                                    //console.log(data);
                                    //apply changes in scope
                                    $scope.$apply(function () {
                                        filesList = [];
                                        // Turn the FileList object into an Array
                                        for (var i = 0; i < data.files.length; i++) {
                                            if (validateFile(data.files[i].name, data.files[i].size)) {
                                                $scope.onAvatarUploading = true;
                                                filesList.push(data.files[i]);
                                                userSrv.uploadAvatar(postUrl, filesList).success(function (dt, st) {
                                                    $scope.$broadcast("avataruploaded", dt);
                                                    //hide indicator
                                                    $scope.onAvatarUploading = false;
                                                }).error(function (dt, st) {
                                                    //alert(dt.message);
                                                    //hide indicator
                                                    $scope.onAvatarUploading = false;
                                                });
                                            }
                                            break;
                                        }
                                    });
                                })
                                .bind('fileuploaddone', function (e, data) {
                                    $scope.onAvatarUploading = false;
                                    //console.log(data);
                                    //scope.$broadcast('avataruploaded', { data: data.jqXHR.responseJSON });
                                });
                        }, 200);
                    }
                }, 200);
            };

            //on avatar upload complete
            $scope.$on("avataruploaded", function (e, params) {
                $scope.onAvatarUploading = false;
                $scope.currentUser.PhotoPath = params.replace(/^~\//g, '');
            });

            $scope.saveInfoSuccessful = false;
            $scope.saveInfoShowMessage = false;
            $scope.saveInfoMessage = '';

            //save user info
            $scope.saveInfo = function (userModel) {
                //show indicator
                $scope.onSubmitting = true;

                userSrv.updateUserInfo(userModel)
                    .success(function () {
                        userSrv.getUserByName(userModel.UserName)
                            .then(function(dt) {
                                //console.log(dt);
                                workContextSrv.setCurrentUser(dt);
                                $rootScope.$broadcast("userSignIn");
                                //hide indicator
                                $scope.onSubmitting = false;
                                $scope.saveInfoSuccessful = true;
                                $scope.saveInfoShowMessage = true;
                                $scope.saveInfoMessage = 'Your info has been saved successful!';
                            });
                    })
                    .error(function (data, status) {
                    //console.log(data);
                    //message 
                    //"The request is invalid."
                    //modelState
                    //Object { model.Password=[1]}
                    //model.Password
                    //["The Password field is required."]

                    //hide indicator
                    $scope.onSubmitting = false;
                });
            };

            //declare following list
            var followingList = [];

            //filter model
            $scope.followingFilter = { name: '' };

            //hide indicator
            $scope.onLoadingUser = false;

            //setup table
            $scope.followingTable = new ngTableParams({
                page: 1,            // show first page
                count: 10,          // count per page
                filter: {
                    //userName: 'M'       // initial filter
                }
            }, {
                counts: [],
                total: followingList.length, // length of data
                getData: function ($defer, params) {
                    // use build-in angular filter
                    var orderedData = params.filter() ?
                           $filter('filter')(followingList, params.filter()) :
                           followingList;
                    params.total(orderedData.length); // set total for recalc pagination
                    $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                },
                $scope: { $data: {} }
            });

            //handle 'reloadFollowingTable' event
            $scope.$on("reloadFollowingTable", function (e, params) {
                //abort all previous request
                $rootScope.$broadcast("abortPendingRequest");

                if ($scope.followingFilter.name === '') {
                    $scope.onLoadingUser = false;
                    followingList = workContextSrv.getCurrentUser().following;
                    $scope.followingTable.reload();
                } else {
                    $scope.onLoadingUser = true;
                    userSrv.searchUser({ nameToSearch: $scope.followingFilter.name }).success(function (dt) {
                        $scope.onLoadingUser = false;
                        followingList = dt;
                        $scope.followingTable.reload();
                    });
                }

            });

            //watch user typing name
            $scope.$watch("followingFilter", function () {
                $scope.$emit("reloadFollowingTable");
            }, true);

            //check following status
            $scope.isFollowed = function (name) {
                var currentUserFollowingList = workContextSrv.getCurrentUser().following;
                for (var i = 0; i < currentUserFollowingList.length; i++) {
                    if (name == currentUserFollowingList[i].userName) {
                        return true;
                    }
                }
                return false;
            };

            $scope.onPasswordLoad = function () {
                //create passwordmodel
                $scope.passwordModel = { oldPassword: '', newPassword: '', confirmNewPassword: '' };

                $scope.savePasswordSuccessful = false;
                $scope.savePasswordShowMessage = false;
                $scope.savePasswordMessage = '';

                function savePasswordSuccessful(data) {
                    if (data === '') {
                        $scope.savePasswordSuccessful = true;
                        $scope.savePasswordShowMessage = true;
                        $scope.savePasswordMessage = 'Your password has been updated successful!';
                        //reset form
                        $scope.userpasswordform.$setPristine();
                        //reset model
                        $scope.passwordModel = angular.copy({ oldPassword: '', newPassword: '', confirmNewPassword: '' });
                    }

                    //hide indicator
                    $scope.onSubmitting = false;
                }

                function savePasswordError(data) {
                    $scope.savePasswordMessage = data;
                    $scope.savePasswordSuccessful = false;
                    $scope.savePasswordShowMessage = true;
                    //hide indicator
                    $scope.onSubmitting = false;
                }

                //save  password
                $scope.savePassword = function (passwordModel) {
                    $scope.savePasswordShowMessage = false;
                    if (passwordModel.newPassword === passwordModel.confirmNewPassword && passwordModel.newPassword.length > 1 && passwordModel.confirmNewPassword.length > 1 && passwordModel.oldPassword.length > 1) {
                        //show indicator
                        $scope.onSubmitting = true;

                        userSrv.updateUserPassword({ name: currentUser.userName, oldp: passwordModel.oldPassword, newp: passwordModel.newPassword }).success(savePasswordSuccessful).error(savePasswordError);
                    }
                };

                $scope.viewUserInfo = function (user) {
                    $rootScope.$broadcast("openPopupViewUserInfo", { userName: user.userName, currentUserList: followingList });
                };
            };

        }
    ]);